//
//  CJExten+StrUI.swift
//  CJCore
//
//  Created by 陈警卫 on 2024-06-14.
//

import UIKit
import Foundation

public extension String {
    
    /// 获取字符串Size
    func cj_size(font: UIFont, expectSize: CGSize, lineBreakMode: NSLineBreakMode = .byWordWrapping) -> CGSize {
        
        let value = self as NSString
        
        var attributes = [NSAttributedString.Key: Any]()
        attributes[NSAttributedString.Key.font] = font
        
        if lineBreakMode != .byWordWrapping {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineBreakMode = lineBreakMode
            attributes[NSAttributedString.Key.paragraphStyle] = paragraphStyle
        }
        
        let origin = NSStringDrawingOptions.usesLineFragmentOrigin
        let lead = NSStringDrawingOptions.usesFontLeading

        let rect = value.boundingRect(with: expectSize, options: [origin, lead], attributes: attributes, context: nil)
        return rect.size
    }
    
    /// 获取字符串height
    func cj_height(font: UIFont, width: CGFloat) -> CGFloat {
        let expectSize =  CGSize(width: width, height: CGFloat(MAXFLOAT))
        let size = cj_size(font: font, expectSize: expectSize)
        return size.height
    }
    
    /// 获取字符串width
    func cj_width(font: UIFont, height: CGFloat) -> CGFloat {
        let expectSize =  CGSize(width: CGFloat(MAXFLOAT), height: height)
        let size = cj_size(font: font, expectSize: expectSize, lineBreakMode: .byWordWrapping)
        return size.width
    }
    
    /// 获取字符串height
    func cj_lableHeight(font: UIFont, width: CGFloat) -> CGFloat {
        let lable = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: 0))
        lable.numberOfLines = 0
        lable.font = font
        lable.text = self
        let size = lable.sizeThatFits(CGSize(width: width, height: CGFloat(MAXFLOAT)))
        return ceil(size.height)
    }
    
    /// 获取字符串width
    func cj_lableWidth(font: UIFont, height: CGFloat) -> CGFloat {
        let lable = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: height))
        lable.numberOfLines = 0
        lable.font = font
        lable.text = self
        let size = lable.sizeThatFits(CGSize(width: CGFloat(MAXFLOAT), height: height))
        return ceil(size.width)
    }
    
}
